package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

/**
 * 购物车
 */
@Controller
public class CartController {

    @Autowired
    private CartFeignClient cartFeignClient;
    //加入购物车
    //http://cart.gmall.com/addCart.html?skuId=9&skuNum=1
    @GetMapping("/addCart.html")
    public String addCart(Long skuId, Integer skuNum, RedirectAttributes redirectAttributes
    , HttpServletRequest request){
        //购物车对象
        cartFeignClient.addToCart(skuId,skuNum);//加入购物车操作
        redirectAttributes.addAttribute("skuId",skuId);
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        redirectAttributes.addAttribute("userId",userId);

        return "redirect:http://cart.gmall.com/toCart.html";
    }
    //去回显成功购物车页面
    @GetMapping("/toCart.html")
    public String toCart(Long skuId,String userId,Model model){
        CartInfo cartInfo = cartFeignClient.getCartInfo(skuId,userId);
        model.addAttribute("cartInfo",cartInfo);
        return "cart/addCart";
    }
    //去购物车结算
    @GetMapping("/cart.html")
    public String toCart(){
        return "cart/index";
    }
}
